package com.education.expenses.facade;

import com.education.expenses.assembler.ReceiptAssembler;
import com.education.expenses.common.dto.GridDTO;
import com.education.expenses.common.dto.ReceiptDTO;
import com.education.expenses.common.dto.WeekSummaryDTO;
import com.education.expenses.eao.UserEAO;
import com.education.expenses.entity.Receipt;
import com.education.expenses.entity.Report;
import com.education.expenses.entity.User;
import com.education.expenses.service.DefaultUserSetupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: apolozkov
 * Date: 8/15/11
 * Time: 5:34 PM
 */

@Service
@Transactional
public class UserFacade {

    @Autowired
    private UserEAO userEAO;

    @Autowired
    private ReceiptAssembler receiptAssembler;

    @Autowired
    private DefaultUserSetupService userSetupService;

    public void defaultUserSetup() {
        userSetupService.createDefaultUsers();
    }

    public void createUser(User user) {
        userEAO.save(user);
    }

    /*Download user from the database and transform to GridDTO*/
    public GridDTO getReport(Long id, Date reportDate, int pageNumber, int pageCount) {
        List<Receipt> list = userEAO.getWeekReceiptListUser(id, reportDate, pageNumber, pageCount);

        GridDTO<ReceiptDTO> gridDTO = new GridDTO<ReceiptDTO>(pageCount, pageNumber);
        gridDTO.setRecordsCount((long) userEAO.getWeekReport(id, reportDate).getReceipts().size());
        gridDTO.setRows(receiptAssembler.toListDTO(list));
        return gridDTO;
    }

    /*To count the all money=) from one report*/
    public GridDTO<WeekSummaryDTO> getPrevWeekSummary(Long id, Date reportDate) {

        GridDTO<WeekSummaryDTO> gridDTO = new GridDTO<WeekSummaryDTO>(1L, 1L);
        gridDTO.setRecordsCount(1L);

        Report report = userEAO.getWeekReport(id, reportDate);

        long meals = 0, lodging = 0, personal = 0, transporation = 0, misc = 0, total = 0;
        for (Receipt receipt : report.getReceipts()) {
            meals += receipt.getMeals();
            lodging += receipt.getLodging();
            personal += receipt.getPersonal();
            transporation += receipt.getTransportation();
            misc += receipt.getMisc();
           // total += receipt.getTotal();
        }
        WeekSummaryDTO weekSummaryDTO = new WeekSummaryDTO(meals, lodging, personal, transporation, misc, total);

        gridDTO.getRows().add(weekSummaryDTO);
        return gridDTO;
    }

    public Report getReport(Long id, Date reportDate) {
        return userEAO.getWeekReport(id, reportDate);
    }
}
